#2022011323+孙月莹
#用户中心蓝图模块
from flask import Blueprint
from flask import render_template,request,redirect,url_for,Response,jsonify
from models import User,House
from settings  import db #导入数据操作对象
import json

#创建蓝图对象
user_page = Blueprint('user_page',__name__)
#1.用户注册路由
@user_page.route('/register',methods=['POST'])
def register():
    #获取前端传来的数据
    username = request.form.get('username')
    password = request.form.get('password')
    email = request.form.get('email')
    #判断用户名是否已经存在 , 如果存在则返回注册失败，如果不存在插入数据表进行注册
    result = User.query.filter(User.name==username).all()
    if len(result)==0:
        #把注册的用户数据写入数据表
        user = User(name=username,password=password,email=email)
        db.session.add(user)
        db.session.commit()
        #把注册成功能信息以及会话组成相应的对象，返回给浏览器
        json_str = json.dumps({'valid':1,'msg':user.name})
        res = Response(json_str)
        res.set_cookie('username',user.name,3600*2)
        return res
    else:
        return jsonify({'valid':0,'msg':'用户名已经存在'})

#2022011323+孙月莹
# 2.用户中心页路由
@user_page.route('/user/<name>',methods=['GET'])
def user(name):
    #扩展任务：判断是否有用户会话，会话的用户名和访问的用户名是否一致
    # 获取当前用户信息
    user = User.query.filter(User.name==name).first()
    # 判断用户是否存在
    if user: #判断用户存在就在查询，查询浏览记录和收藏记录
        # 查询浏览记录,组装成列表中有浏览记录的对象
        seen_id_str = user.seen_id
        if seen_id_str:
            seen_id_list = seen_id_str.split(',')
            seen_house_list = []
            for hid in seen_id_list:
                house = House.query.get(int(hid))
                seen_house_list.append(house)
        else:
            seen_house_list = []
        # 查询收藏记录,组装成列表中有收藏记录的对象
        collect_id_str = user.collect_id
        if collect_id_str:
            collect_id_list=collect_id_str.split(',')
            collect_house_list = []
            for hid in collect_id_list:
                house = House.query.get(int(hid))
                collect_house_list.append(house)
        else:
            collect_house_list = []
        # 返回用户中心页面
        return render_template('user_page.html', user=user,seen_house_list=seen_house_list, collect_house_list=collect_house_list
                           )
    else:
        return redirect('/') #重定项目到首页

#2022011323+孙月莹
# 3.用户登录路由
@user_page.route('/login',methods=['POST'])
def login():
    #获取前端传来的数据
    username = request.form.get('username')
    password = request.form.get('password')
    #判断用户名和密码是否正确
    user = User.query.filter(User.name==username).first()
    if user:
        if user.password == password:
            #用户名和密码都正常，进行正常登录
            json_str = json.dumps({'valid':1,'msg':user.name})
            res = Response(json_str)
            res.set_cookie('username',user.name,3600*2)
            return res
        else:
            return jsonify({'valid':0,'msg':'密码错误'})
    else:
        return jsonify({'valid':0,'msg':'用户名不存在'})

#2022011323+孙月莹
# 4.用户退出登录路由
@user_page.route('/logout')
def logout():
    #在Cookie中删除用户会话
    name = request.cookies.get('username')
    # 用户处于登录状态
    if name:
        result = {'valid':1,'msg':'退出登录成功'}
        json_str = json.dumps(result)
        res = Response(json_str)
        res.delete_cookie('name')
        return res
    # 用户处于未登录状态
    else:
        result = jsonify({'valid':0,'msg':'用户未登录'})

#2022011323+孙月莹
# 5.用户信息修改路由
@user_page.route('/modify/userinfo/<option>',methods=['POST'])
def modify_info(option):
    if option == 'name':
        #获取当前用户名
        y_name = request.form.get('y_name')#获取当前用户名
        name = request.form['name']#获取修改后的用户名
        #根据原来的昵称和新昵称查询用户对象
        user = User.query.filter(User.name==y_name).first()
        other_user = User.query.filter(User.name==name).first()
        if user and not other_user:
            #修改用户名
            user.name = name
            db.session.commit()
            result = {'ok':'1'}
            json_str = json.dumps(result)
            res = Response(json_str)
            res.set_cookie('name',name,3600*2)
            return res
        else:
            return jsonify({'ok':'0'})
    elif option == 'addr':
        #获取新用户名
        y_name = request.form['y_name']
        addr = request.form['addr']
        user = User.query.filter(User.name==y_name).first()
        if user:
            user.addr = addr
            db.session.commit()
            return jsonify({'ok':'1'})
        else:
            return jsonify({'ok':'0'})
    elif option == 'password':
            #获取昵称
            y_name = request.form['y_name']
            password = request.form['password']
            user = User.query.filter(User.name==y_name).first()
            if user:
                user.password = password
                db.session.commit()
                return jsonify({'ok':'1'})
            else:
                return jsonify({'ok':'0'})
    elif option == 'email':
            #获取昵称
            y_name = request.form['y_name']
            email = request.form['email']
            user = User.query.filter(User.name==y_name).first()
            if user:
                user.email = email
                db.session.commit()
                return jsonify({'ok':'1'})
            else:
                return jsonify({'ok':'0'})
    return 'ok'

#2022011323+孙月莹
#6用户收藏记录
@user_page.route('/add/collection/<int:hid>',methods=['GET'])
def add_collect_id(hid):
    #获取当前用户名
    name = request.cookies.get('name')
    #判断用户是否登录
    if name:
        #获取当前用户对象
        user = User.query.filter(User.name==name).first()
        #获取当前用户收藏的房屋id
        collect_id_str = user.collect_id
        #判断当前用户是否收藏过房屋
        if collect_id_str:
            #判断当前房屋是否已经收藏过
            collect_id_list = collect_id_str.split(',')
            set_id = set([int(i) for i in collect_id_list])# 内置集合函数，去重，列表推导式
            if hid in set_id:
                return jsonify({'valid':1,'msg':'房屋已经收藏过了'})
            else:
                new_collect_id_str = collect_id_str + ',' + str(hid)
                user.collect_id = new_collect_id_str
                db.session.commit()
                return jsonify({'valid':1,'msg':'收藏成功'})
        else:
            user.collect_id = str(hid)
            db.session.commit()
            return jsonify({'valid':1,'msg':'收藏成功'})
    else:
        return jsonify({'valid':0,'msg':'用户未登录'})

#2022011323+孙月莹
# 7.用户取消收藏记录路由
@user_page.route('/collect_off',methods=['POST'])
def collect_off():
    #1获取当前用户会话和hid
    name = request.form.get('username')
    hid = request.form.get('house_hid')
    #2获取当前用户名的用户对象，删除id
    user = User.query.filter(User.name==name).first()
    collect_id_str = user.collect_id
    collect_id_list = collect_id_str.split(',')
    if hid in collect_id_list:
        collect_id_list.remove(hid)
        new_collect_id_str = ','.join(collect_id_list)
        user.collect_id = new_collect_id_str
        db.session.commit()
        result = ({'valid':1,'msg':'删除成功'})
        return jsonify(result)
    else:
        result = ({'valid': 0, 'msg': '删除失败'})
        return jsonify(result)

#2022011323+孙月莹
#8清空浏览记录
@user_page.route('del_record',methods=['POST'])
def del_record():
    name = request.form.get('username')
    user = User.query.filter(User.name==name).first()
    if user.seen_id:
        user.seen_id = ""
        db.session.commit()
        return jsonify({'valid':1,'msg':'删除成功'})
    else:
        return jsonify({'valid':0,'msg':'没有浏览记录可以删除'})